package com.qyhl.webtv.module_broke.scoop.addscoop;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideRoundTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.broke.ScoopTopicBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_broke.R;
import com.qyhl.webtv.module_broke.R2;
import com.qyhl.webtv.module_broke.common.BrokeUrl;
import com.qyhl.webtv.module_broke.utils.view.RulePopup;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.analytics.MobclickAgent;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/12/11.
 *
 * @author qyhl
 * 添加视频爆料
 */
@Route(path = ARouterPathConstant.SCOOP_ADD_VIDEO)
public class ScoopAddVideoActivity extends BaseActivity implements ScoopAddContract.ScoopAddView {
    @BindView(R2.id.add_cancel)
    TextView addCancel;
    @BindView(R2.id.add_commit)
    TextView addCommit;
    @BindView(R2.id.scoop_flowlayout)
    TagFlowLayout mTagFlowLayout;
    @BindView(R2.id.scoop_title)
    EditText scoopTitle;
    @BindView(R2.id.current_num)
    TextView currentNum;
    @BindView(R2.id.scoop_anonymous)
    ToggleButton scoopAnonymous;
    @BindView(R2.id.scoop_content)
    EditText scoopContent;
    @BindView(R2.id.add_video)
    ImageButton addVideo;
    @BindView(R2.id.video_player)
    StandardGSYVideoPlayer videoPlayer;
    @BindView(R2.id.delete)
    ImageView delete;
    @BindView(R2.id.video_layout)
    RelativeLayout videoLayout;
    @BindView(R2.id.location)
    TextView mLocation;
    @BindView(R2.id.contact)
    EditText contact;
    @BindView(R2.id.rule)
    TextView rule;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.column_title)
    TextView columnTitle;
    @BindView(R2.id.scoop_content_title)
    TextView scoopContentTitle;
    @BindView(R2.id.layout_one)
    LinearLayout layoutOne;
    @BindView(R2.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R2.id.scoop_type)
    LinearLayout scooptype;

    private List<ScoopTopicBean> tagList;

    private List<LocalMedia> selectedList;

    private String cAnonymous;
    private String cTitle;
    private String cContent;
    private String cAuthor;
    private int cPlateId;
    private String cCreator;
    private String cCreatorAvatar;
    private String cPhone;
    private String cAddress;

    private int isPrivate = 0;
    private List<Integer> tagIndex;
    private Iterator<Integer> iterator;
    private boolean addCommitEnalbe = true;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private String path, address;

    private UpTokenBean data;
    private String mVideoCoverPath;

    private String[] locationChoose = {"是", "否"};
    private int mIndex = 0;

    private LoadingDialog.Builder builder;

    private RequestOptions options;

    private String videoPath;

    private ScoopAddPresenter mPresenter;

    private final static String uploadPath = Environment.getExternalStorageDirectory().getPath() + BrokeUrl.Video;

    private int topId;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.black_40per));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

    }


    @Override
    protected int getContentView() {
        return R.layout.broke_activity_scoop_add_video;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new ScoopAddPresenter(this);
        topId = getIntent().getIntExtra("topId", 0);
        if (topId == 0) {
            tagList = (List<ScoopTopicBean>) getIntent().getExtras().getSerializable("taglist");
            tagList.remove(0);
        }
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
    }



    /**
     * 初始化
     */
    private void initView() {
        mPresenter.getToken();
        if (CommonUtils.getInstance().getSite() == 174) {
            title.setText("添加");
            columnTitle.setText("类型");
            scoopTitle.setHint("标题");
            scoopContentTitle.setText("内容  (");
            rule.setText("《协议》");
        } else {
            title.setText("添加内容");
            columnTitle.setText("内容类型");
            scoopTitle.setHint("内容标题");
            scoopContentTitle.setText("内容  (");
            rule.setText("《问答协议》");
        }
        selectedList = new ArrayList<>();

        //提交等待动画
        builder = new LoadingDialog.Builder(ScoopAddVideoActivity.this);
        builder.setTitle("提交中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);
//        builder.showProgress(false);

        //glide配置
        options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.cover_normal_default)
                .error(R.drawable.cover_normal_default)
                .priority(Priority.HIGH)
                .optionalTransform(new GlideRoundTransform(4));

        //话题选择
        mTagFlowLayout.setMaxSelectCount(1);//最多选一个标签

        mTagFlowLayout.setAdapter(new TagAdapter<ScoopTopicBean>(tagList) {
            @Override
            public View getView(FlowLayout parent, int position, ScoopTopicBean tag) {
                TextView tv = (TextView) LayoutInflater.from(ScoopAddVideoActivity.this).inflate(R.layout.broke_item_scoop_add_tag,
                        mTagFlowLayout, false);
                tv.setText("#" + tag.getName() + "#");
                return tv;
            }
        });

        if (topId == 0) {
            scooptype.setVisibility(View.VISIBLE);
        } else {
            scooptype.setVisibility(View.GONE);
        }
        //--------------------------------------定位--------------------------------------
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(15000);

        mLocationOption.setInterval(2000);

        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

    }


    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(final AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    address = aMapLocation.getDistrict() + aMapLocation.getStreet() + aMapLocation.getStreetNum() + aMapLocation.getAoiName() + aMapLocation.getBuildingId();
                    mLocation.setText(address);
                } else {
                    Toasty.normal(ScoopAddVideoActivity.this, "定位失败！", Toast.LENGTH_SHORT).show();
                    mLocation.setText("所在地址");
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                }
            }
            mLocationClient.stopLocation();
        }
    };

    //初始化视频
    private void initVideo() {
        ImageView imageView = new ImageView(this);
        Glide.with(this)
                .load(mVideoCoverPath)
                .apply(new RequestOptions().centerCrop().error(R.drawable.cover_video_default).placeholder(R.drawable.cover_video_default))
                .into(imageView);
        videoPlayer.setThumbImageView(imageView);//设置封面图

        videoPlayer.setUp(path, true, "");
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                videoPlayer.startWindowFullscreen(ScoopAddVideoActivity.this, true, true);
            }
        });

        if (videoPlayer.isIfCurrentIsFullscreen()) {
            videoPlayer.getBackButton().setVisibility(View.VISIBLE);
        } else {
            videoPlayer.getBackButton().setVisibility(View.GONE);
        }

    }

    /**
     * 监听
     */
    private void setListeners() {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.private_button) {
                    isPrivate = 1;
                } else if (checkedId == R.id.public_button) {
                    isPrivate = 0;
                }
            }
        });
        //协议
        rule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RulePopup rulePopup = new RulePopup(ScoopAddVideoActivity.this);
                rulePopup.setPopupWindowFullScreen(true);
                rulePopup.showPopupWindow();
            }
        });

        //取消
        addCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //提交
        addCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addCommitEnalbe) {
                    addCommitEnalbe = false;
                    builder.show();
                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                setCommit();
                                judgeCommit();//提交判断
                            } else {
                                builder.dismiss();
                                RouterManager.routerLogin(ScoopAddVideoActivity.this, 0);
                                Toasty.normal(ScoopAddVideoActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                addCommitEnalbe = true;
                            }
                        }

                        @Override
                        public void error(String s) {

                        }
                    });

                }
            }
        });

        //坐标
        mLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MPermissionUtils.requestPermissionsResult(ScoopAddVideoActivity.this, 1, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(ScoopAddVideoActivity.this);
                        builder.setTitle("是否显示当前所在地理位置？");
                        builder.setSingleChoiceItems(locationChoose, mIndex, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mIndex = which;
                            }
                        });
                        builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if ("是".equalsIgnoreCase(locationChoose[mIndex])) {
                                    mLocationClient.startLocation();
                                } else {
                                    mLocation.setText("所在地址");
                                }
                                dialog.dismiss();
                            }
                        }).show();
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(ScoopAddVideoActivity.this);
                    }
                });
            }
        });

        //内容字数监听
        scoopContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentNum.setText(scoopContent.getText().toString().length() + "");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //标题
        scoopTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isEmpty(s.toString())) {
                    setCommit();
                } else {
                    resetCommit();
                }
            }
        });

        //添加视频
        addVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(ScoopAddVideoActivity.this)
                        .openGallery(PictureMimeType.ofVideo())//仅视频
                        .imageSpanCount(4)//每行显示4张
                        .previewVideo(true)
                        .maxSelectNum(1)
                        .selectionMode(PictureConfig.MULTIPLE)//单选
                        .isCamera(true)//允许使用相机
                        .isZoomAnim(true)
                        .compress(false)
                        .videoMaxSecond(CommonUtils.getInstance().getSite() == 176 ? 120 : 15)
                        .videoMinSecond(2)
                        .recordVideoSecond(CommonUtils.getInstance().getSite() == 176 ? 120 : 15)
                        .videoQuality(0)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });

        //删除视频
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addVideo.setVisibility(View.VISIBLE);
                videoLayout.setVisibility(View.GONE);
                path = null;
            }
        });

        builder.getmDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
    }

    /**
     * 删除封面图
     */
    private void deleteFile() {
        try {
            File cover = new File(mVideoCoverPath);
            if (cover.exists()) {
                cover.delete();
            }
        } catch (Exception e) {
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                selectedList = PictureSelector.obtainMultipleResult(data);

                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                if (selectedList != null && selectedList.size() > 0) {
                    path = selectedList.get(0).getPath();
                    addVideo.setVisibility(View.GONE);


                    videoLayout.setVisibility(View.VISIBLE);
                    getPicture();//获取封面
                    initVideo();//初始化视频播放器
                }
                break;
            default:
                break;
        }
    }

    /**
     * 提交判断
     */
    private void judgeCommit() {
        //判断标题
        cTitle = scoopTitle.getText().toString();
        if (StringUtils.isEmpty(cTitle)) {
            Toasty.normal(ScoopAddVideoActivity.this, "标题不能为空！", Toast.LENGTH_SHORT).show();
            resetCommit();
            builder.dismiss();
            addCommitEnalbe = true;
            return;
        }

        //判断内容
        cContent = scoopContent.getText().toString();
        if (StringUtils.isEmpty(cContent)) {
//            showMessage("描述内容不能为空！");
//            return;
            cContent = "";
        }

        //判断内容类型
        if (topId != 0) {
            cPlateId = topId;
        } else {
            tagIndex = new ArrayList<>();
            iterator = mTagFlowLayout.getSelectedList().iterator();
            while (iterator.hasNext()) {
                tagIndex.add(iterator.next());
            }

            if (tagIndex.size() > 0) {
                cPlateId = tagList.get(tagIndex.get(0)).getId();
            } else {
                Toasty.normal(ScoopAddVideoActivity.this, "请选择类型！", Toast.LENGTH_SHORT).show();
                resetCommit();
                builder.dismiss();
                addCommitEnalbe = true;
                return;
            }
        }

        //判断联系方式
        cPhone = contact.getText().toString();
        if (StringUtils.isEmpty(cPhone)) {
            cPhone = "";
        }

        //判断地址
        cAddress = mLocation.getText().toString();
        if ("所在地址".equals(cAddress) || StringUtils.isEmpty(cAddress)) {
            cAddress = "";
        }

        //用户信息
        String userName = CommonUtils.getInstance().getUserName();
        String headicon = CommonUtils.getInstance().getUserLogo();
        cCreator = userName;
        cCreatorAvatar = headicon;
        cAuthor = CommonUtils.getInstance().getNickName();

        //是否匿名
        if (scoopAnonymous.isChecked()) {
            cAnonymous = "0";
        } else {
            cAnonymous = "1";
        }

        //视频
        if (path == null) {
//            builder.showProgress(true);
            builder.setTitle("提交中");
            //提交
            mPresenter.commit(cAnonymous, cTitle, cContent, "1", cAuthor, cPlateId + "", cCreator, cCreatorAvatar, "", cPhone, cAddress, null, null, isPrivate, data.getUptoken(), data.getPrefix());
        } else {
//            if (path.contains("qz")) {
//                builder.showProgress(true);
                //提交
                mPresenter.commit(cAnonymous, cTitle, cContent, "1", cAuthor, cPlateId + "", cCreator, cCreatorAvatar, "", cPhone, cAddress, new File(path), mVideoCoverPath, isPrivate, data.getUptoken(), data.getPrefix());
//            } else {
//                builder.setTitle("视频压缩中...");
//                final String name = UUID.randomUUID().toString() + ".mp4";
//                File file = new File(uploadPath);
//                if (!file.exists()) {
//                    file.mkdirs();
//                }
//                videoPath = getExternalCacheDir().getPath() + "/" + name;
//                VideoCompress.compressVideo(path, videoPath, new VideoCompressCallBack() {
//                    @Override
//                    public void onSuccess() {
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
////                                builder.showProgress(true);
//                                builder.setTitle("提交中");
//                                //提交
//                                mPresenter.commit(cAnonymous, cTitle, cContent, "1", cAuthor, cPlateId + "", cCreator, cCreatorAvatar, "", cPhone, cAddress, new File(path), mVideoCoverPath, isPrivate, data.getUptoken(), data.getPrefix());
//                            }
//                        });
//                    }
//
//                    @Override
//                    public void onError() {
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                builder.dismiss();
//                                Toasty.normal(ScoopAddVideoActivity.this, "压缩失败！").show();
//                                addCommitEnalbe = true;
//                            }
//                        });
//
//                    }
//
//                    @Override
//                    public void onPre(int pre) {
//
//                    }
//                });
//            }
        }
    }

    /**
     * 提交失败
     *
     * @param msg
     */
    @Override
    public void commitError(String msg) {
        builder.dismiss();
        Toasty.normal(ScoopAddVideoActivity.this, msg, Toast.LENGTH_SHORT).show();
        resetCommit();
        addCommitEnalbe = true;
    }

    /**
     * 提交成功
     *
     * @param msg
     */
    @Override
    public void commitSuccess(String msg) {
        builder.dismiss();
        Toasty.normal(ScoopAddVideoActivity.this, msg).show();
        addCommitEnalbe = true;
        finish();
    }

    /**
     * 删除压缩视频
     *
     * @param file
     */
    private void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
//            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }

    @Override
    public void cancelCommit() {
        resetCommit();
        addCommitEnalbe = true;
    }

    /**
     * 设置上传进度
     *
     * @param progress
     */
    @Override
    public void setProgress(float progress) {
        int per = (int) (progress * 100);
        if (per % 1 == 0) {
            handler.sendEmptyMessage(per);
        }

    }


    /**
     * 随机生成名称
     *
     * @return
     */
    private String randomName() {
        String name = UUID.randomUUID().toString() + ".png";
        return name;
    }

    /**
     * 获取封面图
     */
    public void getPicture() {
        File file = new File(path);
        //判断对象是否存在，不存在的话给出Toast提示
        if (file.exists()) {
            //提供统一的接口用于从一个输入媒体中取得帧和元数据
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(path);
            Bitmap bitmap = retriever.getFrameAtTime();
            String dirpath = Environment.getExternalStorageDirectory().getPath() + BrokeUrl.PIC;
            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            mVideoCoverPath = Environment.getExternalStorageDirectory().getPath() + BrokeUrl.PIC + File.separator + randomName();
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(mVideoCoverPath);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
                Toasty.normal(ScoopAddVideoActivity.this, "生成封面图失败！", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toasty.normal(ScoopAddVideoActivity.this, "视频路径不存在！", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 设置提交按钮
     */
    private void setCommit() {
        addCommit.setEnabled(false);
        addCommit.setTextColor(getResources().getColor(R.color.global_gray_lv2));
        addCommit.setBackgroundResource(R.drawable.scoop_commit_off);
    }

    /**
     * 恢复提交按钮
     */
    private void resetCommit() {
        addCommit.setEnabled(true);
        addCommit.setTextColor(getResources().getColor(R.color.global_base));
        addCommit.setBackgroundResource(R.drawable.scoop_commit_on);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (GSYVideoManager.backFromWindowFull(this)) {
                    return true;
                } else {
                    finish();
                }
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        StatService.onResume(this);
        StatService.onPageStart(this, "添加视频内容");
        //umeng
        MobclickAgent.onPageStart("添加视频内容");
        MobclickAgent.onResume(this);
        GSYVideoManager.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        StatService.onPause(this);
        StatService.onPageEnd(this, "添加视频内容");
        //umeng
        MobclickAgent.onPageEnd("添加视频内容");
        MobclickAgent.onPause(this);
        GSYVideoManager.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        deleteFile();
        if (StringUtils.isNotEmpty(videoPath)) {
            deleteFile(new File(videoPath));
        }
        GSYVideoManager.releaseAllVideos();

    }



    Handler handler = new MyHandler(this);


    private static class MyHandler extends Handler {
        private final WeakReference<ScoopAddVideoActivity> mActivity;

        public MyHandler(ScoopAddVideoActivity activity) {
            mActivity = new WeakReference<ScoopAddVideoActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ScoopAddVideoActivity scoopAddVideo = mActivity.get();

            scoopAddVideo.builder.setProgress(msg.what);
        }

    }

    @Override
    public void getTokenSuccess(UpTokenBean data) {
        this.data = data;
    }
}
